<template>
	<!-- #ifdef MP-WEIXIN -->
	<uv-navbar
	  :fixed="false"
	  :title="title"
	  left-arrow
	  @leftClick="$onClickLeft"
	/>
	<!-- #endif -->
	<view  class="cart-popup">
		 <view class="top flex justify-between">
		   <text>我的菜单,已点{{ getCartGoodsNumber }}份(<text style="color:#f56c6c">待下单</text>)</text>
		   <text @tap="handleCartClear">清空</text>
		 </view>
		 <scroll-view class="cart-list" scroll-y>
		  <view class="wrapper">
		   <uv-empty mode="car" v-if="cart.length == 0"></uv-empty>
		   <view class="item" v-for="(item, index) in cart" :key="index">
			<view class="left">
			 <view class="name">{{ item.name }}</view>
			 <view class="props">{{ item.valueStr }}</view>
			</view>
			<view class="center">
			 <text>￥{{ item.price }}</text>
			</view>
			<view class="right">
			 <button type="default" plain size="mini" class="btn" hover-class="none"
			  @tap="handleCartItemReduce(index)">
			  <view class="iconfont iconsami-select"></view>
			 </button>
			 <view class="number">{{ item.number }}</view>
			 <button type="primary" class="btn" size="min" hover-class="none"
			  @tap="handleCartItemAdd(index)">
			  <view class="iconfont iconadd-select"></view>
			 </button>
			</view>
		   </view>		
		  </view>
		 </scroll-view>
	 </view>
	 <view  class="cart-popup" v-for="(cart,index2) in otherCart" :key="index2">
	 	 <view class="top flex justify-between">
	 	   <text>{{cart.uname}},已点{{ getCartNumber(cart.content) }}份(<text style="color:#f56c6c">待下单</text>)</text>
	 	 </view>
	 	 <scroll-view class="cart-list" scroll-y>
	 	  <view class="wrapper">
		  <uv-empty mode="car" v-if="cart.length == 0"></uv-empty>
	 	   <view class="item" v-for="(item, index) in cart.content" :key="index">
	 		<view class="left">
	 		 <view class="name">{{ item.name }}</view>
	 		 <view class="props">{{ item.valueStr }}</view>
	 		</view>
	 		<view class="center">
	 		 <text>￥{{ item.price }}</text>
	 		</view>
	 		<view class="right">
	 		 <button type="default" plain size="mini" class="btn" hover-class="none"
	 		  >
	 		  <view class="iconfont iconsami-select"></view>
	 		 </button>
	 		 <view class="number">{{ item.number }}</view>
	 		 <button type="primary" class="btn" size="min" hover-class="none"
	 		 >
	 		  <view class="iconfont iconadd-select"></view>
	 		 </button>
	 		</view>
	 	   </view>		
	 	  </view>
	 	 </scroll-view>
	  </view>
	 <!--已下单-->
	 <view  class="cart-popup" v-if="orderData.appDeskOrderVo">
	 	 <view class="top flex justify-between mb-2" style="background-color: #09b4f1;color: #ffffff;">
	 	   <text>已下单</text>
		   <text>桌位：{{orderData.deskNumber}}</text>
	 	 </view>
	 	 <scroll-view class="cart-list" scroll-y>
	 	  <view class="wrapper2">
			  <view class="item" style="background-color: #fdf6ec;padding: 10rpx 30rpx;margin: 15rpx 0;border-radius: 20rpx;" v-for="(item, index) in orderData.appDeskOrderVo" :key="index">
					<view class="flex align-center">
						<view><uv-avatar :src="item.uavatar"></uv-avatar></view>
						<view class="flex flex-1 justify-between font-size-sm text-color-assist">
							<view class="flex flex-column ml-2">
								<text>{{item.unickname}}</text>
								<text>{{formatDateTime(item.addTime) }}</text>
							</view>
						</view>
					</view>
					<uv-divider text=""></uv-divider>
					<view class="flex align-center" v-for="(good,index2) in item.appDeskOrderGoodsVos" :key="index2">
						<view><image :src="good.image" style="width: 100rpx;height: 100rpx;"></image></view>
						<view class="flex  flex-1 flex-column ml-2 font-size-sm">
							<view class="flex justify-between"><text class="font-weight-bolder">{{good.title}}</text><text style="color: #f56c6c;">{{good.spec}}</text></view>
							<view class="flex justify-between mt-1"><text>¥{{good.price}}</text><text>x{{good.number}}</text></view>
						</view>
				</view>
			</view>		
	 	  </view>
	 	 </scroll-view>
	  </view>
	 <view class="fixed-bottom flex justify-between align-center bg-white ">
	 	<view class="mx-2 ont-weight-light">应付:<text class="text-danger">￥{{ getCartGoodsPrice }}</text></view>
	 	<view><uv-button type="warning" color="#09b4f1" :customStyle="customStyle" size="large" text="去下单" @click="toPay"></uv-button></view>
	 </view>
	 <uv-toast ref="uToast"></uv-toast>
</template>

<script setup>
import {
  ref,
  toRefs,
  computed
} from 'vue'
import {
  orderDetail,
  getShareCart,
  syncCart,
  getDesk
} from '@/api/order'
import { useMainStore } from '@/store/store'
import { storeToRefs } from 'pinia'
import { onLoad,onShow,onUnload,onHide} from '@dcloudio/uni-app'
import { formatDateTime } from '@/utils/util'
import { useWebSocket } from '@/hooks/useWebSocket'
const main = useMainStore()
const { orderType,address, store,location,isLogin,desk,member } = storeToRefs(main)
const title = ref('购物车')
const cart = ref([])
const uToast = ref()
const orderData = ref({})
const otherCart = ref([])
const websocket = ref(null)
const isReconnecting = ref(false)
const combinedCart = ref([])
onShow(() => {
	cart.value = uni.getStorageSync('cart')
	//如果是扫描点餐开启websocket
	if(orderType.value == 'desk'){
		websocketFun()
		getOtherCart()
		detail()
	}
	
})

onUnload(() => {
	websocket.value?.close()
})
onHide(() => {
	websocket.value?.close()
})


const getCartGoodsNumber = computed(() => { //计算购物车总数
	if(cart.value.length == 0) {
		return 0
	}
	return cart.value.reduce((acc, cur) => acc + cur.number, 0)
})
const getCartGoodsPrice = computed(() =>{ //计算购物车总价
	if(combinedCart.value.length == 0) {
		let price0 = cart.value.reduce((acc, cur) => acc + cur.number * cur.price, 0);
		return parseFloat(price0).toFixed(2);
	}
	let price = combinedCart.value.reduce((acc, cur) => acc + cur.number * cur.price, 0);
	return parseFloat(price).toFixed(2);
})
const customStyle = computed(() =>{ 
	return {
		  paddingLeft:'60rpx',
		  paddingRight:'60rpx'
		}
})

//获取订单
const detail =  async() => {
	let data = await getDesk({deskId:desk.value.id});
	if(data && data.lastOrderNo){
		orderData.value = await orderDetail(data.lastOrderNo);
	}
	
}

const getCartNumber = (cart) => {
	if(cart.length == 0) {
		return 0
	}
	return cart.reduce((acc, cur) => acc + cur.number, 0)
}

const handleCartItemAdd = (index) => {
	cart.value[index].number += 1
	uni.setStorageSync('cart', JSON.parse(JSON.stringify(cart.value)))
	if(orderType.value == 'desk'){
		noticeCartInfo({shopId: store.value.id,deskId:desk.value.id,content: cart.value})
	}
}
const handleCartItemReduce = (index) => {
	if (cart.value[index].number === 1) {
		cart.value.splice(index, 1)
	} else {
		cart.value[index].number -= 1
	}
	if (!cart.value.length) {
		cartPopupVisible.value = false
	}
	uni.setStorageSync('cart', JSON.parse(JSON.stringify(cart.value)))
	if(orderType.value == 'desk'){
		noticeCartInfo({shopId: store.value.id,deskId:desk.value.id,content: cart.value})
	}
}
const noticeCartInfo = async(cart) => {
	await syncCart(cart)
}
const handleCartClear = () => { //清空购物车
	uni.showModal({
		title: '提示',
		content: '确定清空购物车么',
		success: ({
			confirm
		}) => {
			if (confirm) {
				cart.value = []
				uni.setStorageSync('cart', JSON.parse(JSON.stringify(cart.value)))
				if(orderType.value == 'desk'){
					getOtherCart()
					noticeCartInfo({shopId: store.value.id,deskId:desk.value.id,content: cart.value})
				}
			}
		}
	})
}
const toPay = () => {
	
	if(cart.value.length == 0){
		uToast.value.show({message:'请先去点餐哦',type: 'error'});
		return;
	}

	if (!isLogin.value) {
		uni.navigateTo({
			url: '/pages/components/pages/login/login'
		})
		return
	} else {
		if (store.value.status == 0) {
			uToast.value.show({message:'不在店铺营业时间内',type: 'error'});
			return;
		}
		// 判断当前是否在配送范围内
		if (orderType.value == 'takeout' && store.value.distance < store.value.far) {
			uToast.value.show({message:'选中的地址不在配送范围',type: 'error'});
			return;
		}
	
		uni.showLoading({
			title: '加载中'
		})
		if(combinedCart.value.length > 0){
			uni.setStorageSync('cart', JSON.parse(JSON.stringify(combinedCart.value)))
		}else{
			uni.setStorageSync('cart', JSON.parse(JSON.stringify(cart.value)))
		}
		

		uni.navigateTo({
			url: '/pages/components/pages/pay/pay'
		})
	}

	uni.hideLoading()
}
const getOtherCart = async() => {
	let data = await getShareCart({shopId:store.value.id,deskId:desk.value.id})
	if(data){
		otherCart.value = data
		let newOtherCart = []
		otherCart.value.forEach((item, index) => {
			item.content.forEach((item2, index2) => {
				newOtherCart.push(item2);
			});
		});
		combinedCart.value = [...newOtherCart, ...cart.value];
	}
}
const websocketFun = () => {
	 websocket.value = useWebSocket({
	    // 连接成功
	    onConnected: async () => {},
	    // 收到消息
	    onMessage: async (data) => {
		  if(data.type == 'sync-menu-msg'){
			  let content = JSON.parse(data.content)
			  console.log('content：',content);
			  console.log('deskId：',content.deskId);
			  console.log('cartMsgVoList：',content.cartMsgVoList);
			  if((store.value.id == content.shopId) && (desk.value.id == content.deskId)){
				  if(content.uid != member.value.id){
					  const index = otherCart.value.findIndex(item => {
					  	return (item.shopId === content.shopId) && (item.deskId === content.deskId) && (item.uid === content.uid)
					  })
					  if(index > -1){
						  otherCart.value[index] = content
					  }else{
						  otherCart.value.push(content)
					  }	  
					  
					  let newOtherCart = []
					  otherCart.value.forEach((item, index) => {
					  	item.content.forEach((item2, index2) => {
					  		newOtherCart.push(item2);
					  	});
					  });
					  combinedCart.value = [...newOtherCart, ...combinedCart.value];
				  }
			  }
		  }
	    },
	});
}
</script>

<style lang="scss" scoped>
.cart-popup {
		.top {
			background-color: $bg-color-primary;
			//color: $color-primary;
			color: #5A5B5C;
			padding: 10rpx 30rpx;
			font-size: 24rpx;
			text-align: right;
		}
		.cart-list {
			background-color: #ffffff;
			width: 100%;
			overflow: hidden;
			min-height: 1vh;
			max-height: 60vh;
			
			.wrapper2 {
				height: 100%;
				//display: flex;
				flex-direction: column;
				padding: 0 10rpx;
				margin-bottom: 156rpx;
			}
	
			.wrapper {
				height: 100%;
				display: flex;
				flex-direction: column;
				padding: 0 30rpx;
				margin-bottom: 100rpx;
	
				.item {
					display: flex;
					justify-content: space-between;
					align-items: center;
					padding: 30rpx 0;
					position: relative;
	
					&::after {
						content: ' ';
						position: absolute;
						bottom: 0;
						left: 0;
						width: 100%;
						background-color: $border-color;
						height: 2rpx;
						transform: scaleY(0.6);
					}
	
					.left {
						flex: 1;
						display: flex;
						flex-direction: column;
						overflow: hidden;
						margin-right: 30rpx;
	
						.name {
							font-size: $font-size-sm;
							color: $text-color-base;
						}
						.props {
							color: $text-color-assist;
							font-size: 24rpx;
							overflow: hidden;
							text-overflow: ellipsis;
							white-space: nowrap;
						}
					}
	
					.center {
						margin-right: 120rpx;
						font-size: $font-size-base;
					}
	
					.right {
						display: flex;
						align-items: center;
						justify-content: space-between;
	
						.btn {
							width: 46rpx;
							height: 46rpx;
							border-radius: 100%;
							padding: 0;
							text-align: center;
							line-height: 46rpx;
						}
	
						.number {
							font-size: $font-size-base;
							width: 46rpx;
							height: 46rpx;
							text-align: center;
							line-height: 46rpx;
						}
					}
				}
			}
		}
	}
</style>
